//
//  WXSpeech.m
//  YouYiKuProject
//
//  Created by xue on 2018/12/27.
//  Copyright © 2018年 xuezi. All rights reserved.
//

#import "WXSpeech.h"
#import <AVFoundation/AVFoundation.h>
#import "WXVoiceSDK.h"

#define DEFINE_SHARED_INSTANCE_USING_BLOCK(block) \
static dispatch_once_t pred = 0; \
static id _sharedObject = nil; \
dispatch_once(&pred, ^{ \
_sharedObject = block(); \
}); \
return _sharedObject; \


@interface WXSpeech ()<WXSpeechRecognizerViewDelegate, WXVoiceDelegate>
{
@public
    WXSpeechRecognizerView *_speechRecognizerView;
}
@end

@implementation WXSpeech

+ (WXSpeech *)sharedInstance{
    
    DEFINE_SHARED_INSTANCE_USING_BLOCK(^{
        
        return [[self alloc] init];
    });
}

- (id)init{
    
    self = [super init];
    if (self) {
        
    }
    return self;
}

#pragma mark -----------WXVoiceDelegate------------

// 调用我们的引擎之后可能收到的一些有用和错误信息都在下面的回调当中返回！！！！！！！！！！！！！！！！！！！！！！！！
- (void)voiceInputResultArray:(NSArray *)array{
    //一旦此方法被回调，array一定会有一个值，所以else的情况不会发生，但写了会更有安全感的
    NSLog(@"-------------call back voiceInputResultArray%@----------------",array);
    if (array && array.count>0) {
        WXVoiceResult *result=[array objectAtIndex:0];
        [_speechRecognizerView setResultText:result.text];
    }else{
        [_speechRecognizerView setResultText:@""];
    }
}
- (void)voiceInputMakeError:(NSInteger)errorCode{
    NSLog(@"%ld",(long)errorCode);
    [_speechRecognizerView setErrorCode:errorCode];
}
- (void)voiceInputVolumn:(float)volumn{
    [_speechRecognizerView setVolumn:volumn];
}
- (void)voiceInputWaitForResult{
    NSLog(@"-------------call back voiceInputWaitForResult----------------");
    //    [_speechRecognizerView finishRecorder];
}
- (void)voiceInputDidCancel{
    [_speechRecognizerView didCancel];
}

#pragma mark -----------ViewDelegate------------

// 开始和结束识别主要就是像如下两个函数里这么调用我们引擎的接口！！！！！！！！！！！！！！！！！！
- (BOOL)start{
    return [[WXVoiceSDK sharedWXVoice] startContinusMode];
}
- (void)finishRecorder{
    [[WXVoiceSDK sharedWXVoice] stopContinusMode];
    
    [_speechRecognizerView didFinish];
}
- (void)cancel{
    [[WXVoiceSDK sharedWXVoice] cancel];
}


/////添加语音识别view
-(void)addSpeechRecognizerView:(RootWebViewController*)root{
    
    CGRect frame = [UIScreen mainScreen].bounds;
    frame.size.height -=64;
    
    _speechRecognizerView = [[WXSpeechRecognizerView alloc] initWithFrame:frame];
    _speechRecognizerView.delegate = self;
    [root.view addSubview:_speechRecognizerView];
    
    // SDK
    WXVoiceSDK *speechRecognizer = [WXVoiceSDK sharedWXVoice];
    //可选设置
    speechRecognizer.silTime = 10.5f;
    //必选设置
    speechRecognizer.delegate = self;
    [speechRecognizer setAppID:@"wx725aa31f5a2da818"];
    
    [speechRecognizer setDomain:10];
    //[speechRecognizer setContinuousMode:true];
    //[speechRecognizer setMaxResultCount:3];
    
}
@end
